package net.huashitong.common.controller;

import com.alibaba.fastjson.JSONArray;
import com.ckfinder.connector.ServletContextFactory;
import com.sirdc.modules.core.config.Global;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.entity.SysFile;
import com.sirdc.modules.sys.service.SysFileService;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import com.sirdc.modules.utils.UUIDGenerator;
import com.sirdc.modules.utils.date.DateUtils;
import com.sirdc.modules.utils.file.FileUtils;
import jodd.io.FileUtil;
import net.huashitong.common.entity.SysBriefing;
import net.huashitong.common.entity.WeekDocument;
import net.huashitong.common.filter.SysBriefingFilter;
import net.huashitong.common.filter.WeekDocumentFilter;
import net.huashitong.common.service.SysBriefingService;
import net.huashitong.common.service.WeekDocumentService;
import net.huashitong.supervision.task.entity.BriefCategory;
import net.huashitong.supervision.task.entity.TaskCategory;
import net.huashitong.supervision.task.filter.BriefCategoryFilter;
import net.huashitong.supervision.task.service.BriefCategoryService;
import net.huashitong.supervision.task.service.TaskCategoryService;
import net.huashitong.util.UtilsTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.UriUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 简报管理
 */
@Controller
@RequestMapping(value = "/common/releaseBriefing")
public class SysBriefingController extends JsonBaseController {
    @Autowired
    private TaskCategoryService categoryService;
    @Autowired
    private SysBriefingService sysBriefingService;
    @Autowired
    private SysFileService fileservice;
    @Autowired
    private BriefCategoryService briefCategoryService;
    @Autowired
    private WeekDocumentService weekDocumentService;

    @Override
    protected String getView(String s) {
        return "/modules/common/releaseBriefing/" + s;
    }

    /**
     * 返回发布简报页面
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public String releaseBriefing() {
        return getView("query");
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public JqGrid initBriefing(SysBriefingFilter filter) {
        List<SysBriefing> list = sysBriefingService.queryByFilter(filter);
        return coverJqGrid(filter, list);
    }

    @ResponseBody
    @RequestMapping(value = "/getBriefing", method = RequestMethod.GET)
    public Message getBriefing() {
        SysBriefingFilter filter = new SysBriefingFilter();
        filter.setStatus("1");
        List<SysBriefing> list = sysBriefingService.queryByFilter(filter);
        return coverMessage(UtilsTools.CODE, "查询成功", list);
    }

    @ResponseBody
    @RequestMapping(value = "/getBriefing/{id}", method = RequestMethod.GET)
    public Message getBriefing(@PathVariable String id) {
        SysBriefing sysBriefing = sysBriefingService.getById(id);
        if (sysBriefing == null) {
            sysBriefing = new SysBriefing();
        }
        return coverMessage(UtilsTools.CODE, "查询成功", sysBriefing);
    }

    @RequestMapping("/filter")
    public String filter(Model model, @ModelAttribute SysBriefingFilter filter) {
        List<String> types = sysBriefingService.getTypes();
        model.addAttribute("types", types);
        return getView("filter");
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String showEditView(Model model, @PathVariable String id) {
        SysBriefing sysBriefing = sysBriefingService.getById(id);
        model.addAttribute("SysBriefingFilter", sysBriefing);
        return getView("form");
    }

    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Message update(@ModelAttribute SysBriefingFilter filter) {
        if (StringUtils.isBlank(filter.getSysId())) {
            return coverMessage(UtilsTools.ERROR, "简报不存在");
        }
        SysBriefing sysBriefing = sysBriefingService.getById(filter.getSysId());
        if (ObjectUtils.isBlank(sysBriefing)) {
            return coverMessage(UtilsTools.ERROR, "简报不存在");
        }
        if (!"2".equals(sysBriefing.getStatus())) {
            return coverMessage(UtilsTools.ERROR, "请先下架简报");
        }
        if (StringUtils.isNotBlank(sysBriefing.getType()) && !sysBriefing.getType().equals(filter.getType())) {
            return coverMessage(UtilsTools.ERROR, "简报类型不允许修改，请重新创建");
        }
        sysBriefing = new SysBriefing();
        UtilsTools.copyPro(filter, sysBriefing);
        sysBriefingService.update(sysBriefing);
        return coverMessage(UtilsTools.CODE);
    }

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String showAddView(@ModelAttribute SysBriefingFilter filter, Model model) {
        //List<String> types = sysBriefingService.getTypes();
        List<BriefCategory> list = briefCategoryService.query();
        List<WeekDocument> weekDocuments = weekDocumentService.query();

//        List<TaskCategory> types = categoryService.query();
        model.addAttribute("BriefCategorys", list);
        model.addAttribute("weekDocuments", weekDocuments);

//        model.addAttribute("types",types);
        return getView("form");
    }

    /**
     * 周文档表格
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryWeekDoc", method = RequestMethod.POST)
    public JqGrid queryWeekDoc(WeekDocumentFilter filter) {
        List<WeekDocument> weekDocuments = weekDocumentService.queryFilter(filter);
        return coverJqGrid(filter, weekDocuments);
    }

    @RequestMapping(value = "/weekcreate", method = RequestMethod.GET)
    public String showWeekAddView(@ModelAttribute SysBriefingFilter filter, Model model) {
        //List<String> types = sysBriefingService.getTypes();

        List<BriefCategory> types = briefCategoryService.query();
        model.addAttribute("SysBriefingFilter", filter);
        model.addAttribute("types", types);
        return getView("form2");
    }

    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Message create(@ModelAttribute SysBriefingFilter filter) {
        SysBriefing sysBriefing = new SysBriefing();
        UtilsTools.copyPro(filter, sysBriefing);
        sysBriefing.setStatus("0");
        sysBriefingService.save(sysBriefing);
        return coverMessage(UtilsTools.CODE);
    }

    /**
     * 创建周文档
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/weekcreate", method = RequestMethod.POST)
    public Message weekcCreate(@ModelAttribute WeekDocumentFilter filter) {
       /* SysBriefing sysBriefing = new SysBriefing();
        UtilsTools.copyPro(filter,sysBriefing);
        sysBriefing.setStatus("0");
        sysBriefing.setDocType("1");
        sysBriefingService.save(sysBriefing);*/
        String period = filter.getPeriod();
        List<WeekDocument> query = weekDocumentService.query();
        if (ObjectUtils.isNotBlank(query)){
            for (WeekDocument weekDocument : query) {
                //将以前的先下架
                weekDocument.setState("0");
                weekDocumentService.update(weekDocument);
                if (period.equals(weekDocument.getPeriod())) {
                    return coverMessage("500", "周期重复");
                }
            }
        }
        WeekDocument weekDocument = new WeekDocument();
        UtilsTools.copyPro(filter, weekDocument);
        //默认当前上传的上架
        weekDocument.setState("1");
        weekDocumentService.save(weekDocument);
        return coverMessage(UtilsTools.CODE);
    }

    /**
     * 周文档上下架
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateWeekState")
    public Message updateWeekState(String id, String state) {
        WeekDocument weekDocument = weekDocumentService.getById(id);
        List<WeekDocument> list = weekDocumentService.query();
        if (ObjectUtils.isNotBlank(weekDocument)) {
            for (WeekDocument document : list) {
                //先将所有的下架
                document.setState("0");
                weekDocumentService.update(document);
            }
            //只上架当前
            weekDocument.setState(state);
            weekDocumentService.update(weekDocument);
            return coverMessage(UtilsTools.CODE,"成功");
        }else{
            return coverMessage(UtilsTools.ERROR,"失败");
        }

    }

    /**
     * 反回周文档PDF的路径
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getWeekDoc")
    public Message getWeekDoc(){
        WeekDocumentFilter filter = new WeekDocumentFilter();
        filter.setState("1");
        List<WeekDocument> documents = weekDocumentService.queryFilter(filter);
        if (documents.size()!=1){
            return coverMessage(UtilsTools.ERROR);
        }else{
            String weekDoc = documents.get(0).getWeekDoc();
            if (StringUtils.isBlank(weekDoc)){
                logger.error("500","请求的文件不存在" );
                return coverMessage("500","文件不存在");
            }
            return coverMessage(UtilsTools.CODE,"成功",weekDoc);
        }
    }
    @ResponseBody
    @RequestMapping(value = "/delete/{id}")
    public Message forceDelete(@PathVariable List<String> id) {
        sysBriefingService.batchDelete(id);
        return coverMessage(UtilsTools.CODE);
    }

    @ResponseBody
    @RequestMapping(value = "/checkTitle", method = RequestMethod.POST)
    public Message checkTitle(@ModelAttribute SysBriefingFilter filter) {
        List<SysBriefing> sysBriefings = sysBriefingService.checkTitle(filter);
        if (sysBriefings != null && sysBriefings.size() > 0) {
            return coverMessage(UtilsTools.ERROR, "标题重复");
        }
        return coverMessage(UtilsTools.CODE);
    }

    /**
     * 简报上下架管理
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    public Message updateStatus(@ModelAttribute SysBriefingFilter filter) {
        if (StringUtils.isBlank(filter.getSysId())) {
            return coverMessage(UtilsTools.ERROR, "简报不存在");
        }
        SysBriefing sysBriefing = sysBriefingService.getById(filter.getSysId());
        if (ObjectUtils.isBlank(sysBriefing)) {
            return coverMessage(UtilsTools.ERROR, "简报不存在");
        }
        if ("1".equals(filter.getStatus()) || "2".equals(filter.getStatus())) {
            sysBriefing.setStatus(filter.getStatus());
            sysBriefingService.update(sysBriefing);
            return coverMessage(UtilsTools.CODE);
        }
        return coverMessage(UtilsTools.ERROR, "无效的修改");
    }


    @ResponseBody
    @RequestMapping("/uploadBatch")
    public Message uplaodfile(@RequestParam MultipartFile files) {
        SysFile sysfile = new SysFile();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            String originalFilename = files.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String baseDirectory = Global.getUploadBaseDir();
            String filename = System.currentTimeMillis() + UUIDGenerator.randomBase62(5);
            String relativeDirectory = DateUtils.getDate("yyyy/MM/dd/");
            String relativeFilePath = relativeDirectory + filename + "." + fileType;
            String absoluteDirectory = baseDirectory + relativeDirectory;
            String absoluteFilePath = baseDirectory + relativeFilePath;
            FileUtils.createDirectory(FileUtils.path(absoluteDirectory));
            FileUtil.writeBytes(absoluteFilePath, files.getBytes());
            String baseUserUri = "/" + Global.USER_DIR + "/";
            String rootPath = ServletContextFactory.getServletContext().getContextPath();
            if (rootPath.length() == 1) {
                rootPath = "";
            }
            String url = baseUserUri + relativeFilePath;
            map.put("sysid", sysfile.getSysId());
            map.put("src", absoluteFilePath);
            System.out.println("保存路径：" + url);
            return coverMessage(UtilsTools.CODE, "保存成功", map);
        } catch (Exception e) {
            return coverMessage(UtilsTools.ERROR);
        }
    }


    //上传后台
    @RequestMapping(value = "uploadEditorImg", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public synchronized Map<String, Object> uploadEditorImg(HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
        Map<String, Object> map = new HashMap<>();
        Iterator<String> iterator = mr.getFileNames();
        while (iterator.hasNext()) {
            MultipartFile multipartFile = mr.getFile(iterator.next());
            String oldFileName = multipartFile.getOriginalFilename();
            String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
            String folder = sdf.format(new Date());
            String basePath = Global.getUploadBaseDir();
            String frontPath = basePath + "briefing" + File.separator + folder;
            File dir = new File(frontPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 新文件名称
            String newFileName = System.currentTimeMillis() + UUIDGenerator.randomBase62(5);
            String filePath = folder + newFileName + suffix;
            String fullFilePath = frontPath + newFileName + suffix;
            File newFile = new File(frontPath + newFileName + suffix);
            multipartFile.transferTo(newFile);
            map.put("oldFileName", oldFileName);
            map.put("newFileName", newFileName);
            map.put("filePath", filePath);
            map.put("fullFilePath", fullFilePath);
            map.put("path", "/common/releaseBriefing/showEditorImg?fullpath=" + filePath);
        }
        return map;
    }


    //展示
    @RequestMapping(value = "showEditorImg", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public void showEditorImg(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fullpath = request.getParameter("fullpath"); // 文件名
        FileInputStream fileInputStream = null;
        OutputStream outStream = null;
        String basePath = Global.getUploadBaseDir();
        try {
            fileInputStream = new FileInputStream(basePath + "briefing" + File.separator + fullpath);
            int i = fileInputStream.available(); // 得到文件大小
            byte data[] = new byte[i];
            fileInputStream.read(data); // 读数据
            response.setContentType("image/*"); // 设置返回的文件类型
            outStream = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
            outStream.write(data); // 输出数据
        } catch (Exception e) {
            System.out.println("系统找不到文件：" + fullpath);
        } finally {
            if (outStream != null) {
                outStream.flush();
                outStream.close();
            }
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        }
    }


    //文件上传
    @ResponseBody
    @RequestMapping("/filesUpload/uploadBatch")
    public String filesUploaduplaodfile(HttpServletRequest request, String content) {
        MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
        List<MultipartFile> fileList = req.getFiles("file");
        String str = null;
        Message msg = new Message();
        if (fileList == null || fileList.size() == 0) {
            msg.setCode(UtilsTools.ERROR);
            msg.setMessage("没有上传文件");
            return JSONArray.toJSONString(msg);
        }
        //System.out.println(projectStage);
        Map<String, Object> mao = new HashMap<String, Object>();
        Map<String, String> fileArr = new HashMap<>();
        try {
            for (MultipartFile file : fileList) {
                String originalFilename = file.getOriginalFilename();
                String prefix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toUpperCase();
                if (prefix.equals("BMP") || prefix.equals("PNG") || prefix.equals("GIF") || prefix.equals("JPG") || prefix.equals("JPEG")) {

                } else {
                    msg.setCode(UtilsTools.ERROR);
                    msg.setMessage("文件格式不正确");
                    return JSONArray.toJSONString(msg);
                }
                if (file.getSize() > 2097152) {
                    return handleTooBigFiles(fileList, msg);
                }

                /**
                 注意这里获取的个数，是根据前端form表单里有几个，type=file来决定的，
                 比如你虽然只点选了一个文件，上传，但这里实际上回有两个MultipartFile对 象，只不过其中一个MutipartFile的文件名会为空，这就是为什么下边会有个判断文件名
                 为空的步骤**/
                //SysFile sysfile = new SysFile();
                String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                String baseDirectory = Global.getUploadBaseDir();
                String finalFilename = System.currentTimeMillis() + UUIDGenerator.randomBase62(5);
                String relativeDirectory = DateUtils.getDate("yyyy/MM/dd/");
                String relativeFilePath = relativeDirectory + finalFilename + "." + fileType;
                String absoluteDirectory = baseDirectory + relativeDirectory;
                String absoluteFilePath = baseDirectory + relativeFilePath;
                FileUtils.createDirectory(FileUtils.path(absoluteDirectory));
                FileUtil.writeBytes(absoluteFilePath, file.getBytes());
                String baseUserUri = "/" + Global.USER_DIR + "/";
                String rootPath = ServletContextFactory.getServletContext().getContextPath();
                if (rootPath.length() == 1) {
                    rootPath = "";
                }
                //sysfile.setFilename(finalFilename);
                //sysfile.setFileType(fileType);
                //sysfile.setUrl(baseUserUri + relativeFilePath);
                //fileservice.save(sysfile);
                //fileArr.put(originalFilename,sysfile.getSysId());
            }

            //filesave.fileSave(sysfile, files);
            //替换过的内容
            mao.put("content", "");
//			str = "code:'200',data:{'sysid':"+sysfile.getSysId()+"}";
            msg.setCode(UtilsTools.CODE);
            msg.setData(mao);
            str = JSONArray.toJSONString(msg);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str;
    }


    private String handleTooBigFiles(List<MultipartFile> fileList, Message msg) {
        List<String> big = new ArrayList<>();
        for (MultipartFile file : fileList) {
            if (file.getSize() > 2097152) {
                big.add(file.getOriginalFilename());
            }
        }
        msg.setCode(UtilsTools.ERROR);
        msg.setMessage("单个文件过大，所有在不符合列表中的文件请压缩");
        msg.setData(big);
        return JSONArray.toJSONString(msg);
    }

    /**
     * 返回简报类型页面
     *
     * @return
     */
    @RequestMapping("/briefCategory")
    public String briefCategory(Model model) {
        List<BriefCategory> list = briefCategoryService.queryFilter(new BriefCategoryFilter());
        model.addAttribute("list", list);
        return getView("briefCategory");
    }

    @ResponseBody
    @RequestMapping(value = "/briefCategory", method = RequestMethod.POST)
    public JqGrid briefCategory(BriefCategoryFilter filter) {
        List<BriefCategory> list = briefCategoryService.queryFilter(filter);
        return coverJqGrid(filter, list);
    }

    @ResponseBody
    @RequestMapping(value = "/briefCategoryList", method = RequestMethod.POST)
    public List<BriefCategory> briefCategoryList(BriefCategoryFilter filter) {
        List<BriefCategory> list = briefCategoryService.queryFilter(filter);
        return list;
    }

    /**
     * 新增分类
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addCategory", method = RequestMethod.POST)
    public Message addCategory(BriefCategoryFilter filter) {
        if (StringUtils.isNotBlank(filter.getCategory())) {
            BriefCategory briefCategory = new BriefCategory();
            briefCategory.setCategory(filter.getCategory());
            briefCategoryService.save(briefCategory);
            return coverMessage("200");
        } else {
            return coverMessage("500");
        }
    }

    /**
     * 删除分类
     *
     * @param sysId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteCategory/{sysId}", method = RequestMethod.POST)
    public Message delete(@PathVariable List<String> sysId) {
        if (ObjectUtils.isNotBlank(sysId)) {
            briefCategoryService.batchDelete(sysId);
            return coverMessage("200");
        } else {
            return coverMessage("500");
        }
    }

}
